//聊天
let mongoose = require('mongoose');
const weChat=require('../../util/wechat');
module.exports={
    add:async function(options={channel:'World',type:'0',message:'这是消息',data:{}}){
        // if(options.channel=='World'){ //判断能量是否足够
        //     options.self.refresh();
        //     if(options.self.store.power<=0){
        //         return {code:300};
        //     }
        //     options.self.store.power-=1;
        // }
        let checkResult=await weChat.msgSecCheck(options.message);
        if(!checkResult){
            throw new Error('根据政策法规，消息包含非法字符！');
        }

        let ChatMessageModel=mongoose.models['ChatMessage'];
        await ChatMessageModel.create({
            userId:options.self._id.toString(),
            channel:options.channel,
            // x:options.self.city.x,
            // y:options.self.city.y,
            type:parseInt(options.type),
            message:options.message,
            data:options.data,
            addTime:new Date().getTime()
        });
    },
    list:async function(options={channel:'World',lastMessageId:''}){
        let ChatMessageModel=mongoose.models['ChatMessage'];
        let GameUserModel=mongoose.models['GameUser'];
        let list=[];
        let result=[];
        if(!options.lastMessageId){
            options.lastMessageId='000000000000000000000000';
        }
        //if(options.channel=='World'){
            list=await ChatMessageModel.find({channel:options.channel,_id:{$gt:options.lastMessageId}}).sort({addTime:-1}).limit(20);
        // }else{
        //     //附近的聊天
        //     list=await ChatMessageModel.find({channel:options.channel,_id:{$gt:options.lastMessageId},x:{$gte:options.self.city.x-50,$lte:options.self.city.x+50},y:{$gte:options.self.city.y-50,$lte:options.self.city.y+50}}).sort({addTime:-1}).limit(20);
        // }
        let userIds=[];
        for(let i=0;i<list.length;i++){
            if(!userIds.includes(list[i].userId)){
                userIds.push(list[i].userId);
            }
        }
        let users = await GameUserModel.find({_id:{$in:userIds}});
        for(let i=0;i<list.length;i++){
            let obj={};
            let user=users.find((item)=>{return item._id.toString()===list[i].userId;});
            if(!user) continue;
            Object.assign(obj,list[i].getMessage(),{user:user.getMessage()});
            result.push(obj);
        }
        return result;
    }
};